// models/materialsListModel.js
const db = require('../db');

const MaterialsList = {
    // 获取所有材料
    async getAll() {
        const [rows] = await db.execute('SELECT * FROM materials_list WHERE status != 2');
        return rows;
    },

    // 根据 ID 获取材料
    async getById(id) {
        const [rows] = await db.execute('SELECT * FROM materials_list WHERE id = ? AND status != 2', [id]);
        return rows[0];
    },

    // 创建材料
    async create(data) {
        const sql = `
          INSERT INTO materials_list 
          (name, code, specification, supplier, project, type, expected_amount, purchase_amount, expected_cost, cost, unit, rate, purchaser, remark, unit_price)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;
        const params = [
            data.name, data.code, data.specification, data.supplier, data.project, data.type,
            data.expected_amount, data.purchase_amount, data.expected_cost, data.cost,
            data.unit, data.rate, data.purchaser, data.remark, data.unit_price
        ];
        const [result] = await db.execute(sql, params);
        return result.insertId;
    },

    // 更新材料
    async update(id, data) {
        const sql = `
          UPDATE materials_list SET
          name = ?, code = ?, specification = ?, supplier = ?, project = ?, type = ?,
          expected_amount = ?, purchase_amount = ?, expected_cost = ?, cost = ?,
          unit = ?, rate = ?, purchaser = ?, remark = ?, unit_price = ?
          WHERE id = ? AND status != 2
        `;
        const params = [
            data.name, data.code, data.specification, data.supplier, data.project, data.type,
            data.expected_amount, data.purchase_amount, data.expected_cost, data.cost,
            data.unit, data.rate, data.purchaser, data.remark, data.unit_price, id
        ];
        const [result] = await db.execute(sql, params);
        return result.affectedRows;
    },

    // 软删除材料
    async softDelete(id) {
        const [result] = await db.execute('UPDATE materials_list SET status = 2 WHERE id = ?', [id]);
        return result.affectedRows;
    }
};

module.exports = MaterialsList;
